package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Location;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets a {@link Location}'s data via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterLocationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String country = req.getParameter("country");
		String city = req.getParameter("city");
		String zip = req.getParameter("zip");
		String streetNr = req.getParameter("streetNr");
		String name = req.getParameter("name");

		if (country == null || city == null || zip == null || streetNr == null) {
			resp.setStatus(400);
			resp.getWriter().println("Please fill in all fields");
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			Query query = pm.newQuery(Location.class);
			query.setFilter("name == nameParam");
			query.declareParameters("String nameParam");
			query.setOrdering("name desc");
			
			List<Location> results = (List<Location>) query.execute(name);
			
			if (results.isEmpty()) {
				Location location = new Location(country, city, zip, streetNr,
						name);
				try {
					pm.makePersistent(location);
					pm.flush();
					
					resp.setStatus(200);
					resp.getWriter().println("Location saved successfully!");
				} catch (Exception e) {
					e.printStackTrace();
					resp.setStatus(400);
				} finally {
					pm.close();
				}
			} else {
				resp.setStatus(400);
				resp.getWriter().println("Location already exists");
			}

		}
	}
}
